package com.heiam.search.service.impl;

import com.heiam.search.service.ApAssociateWordsService;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.search.dto.UserSearchDto;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.search.suggest.Suggest;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.SuggestBuilders;
import org.elasticsearch.search.suggest.completion.CompletionSuggestion;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Service
public class ApAssociateWordsServiceImpl implements ApAssociateWordsService {

    @Resource
    private RestHighLevelClient restHighLevelClient;

    //搜索自动补全内容
    @Override
    public ResponseResult search(UserSearchDto userSearchDto) throws IOException {

        //构建请求
        SearchRequest request = new SearchRequest("app_article_info");
        request.source().suggest(new SuggestBuilder()
                .addSuggestion("suggestions", SuggestBuilders.completionSuggestion("suggestion")
                        .prefix(userSearchDto.getSearchWords())
                        .skipDuplicates(true)
                        .size(10)
                ));

        //发送请求
        SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);

        //解析响应结果
        CompletionSuggestion suggestions=response.getSuggest().getSuggestion("suggestions");
        List<CompletionSuggestion.Entry.Option> optionList = suggestions.getOptions();
        List<String> list=new ArrayList<>();
        //将获得的结果存入结果集
        for (CompletionSuggestion.Entry.Option option : optionList) {
            String text = option.getText().toString();
            list.add(text);
        }

        return ResponseResult.okResult(list);
    }
}
